package org.skatiger.jrove.renderer.html;

import java.io.IOException;

import org.skatiger.jrove.ResponseWriter;
import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.JroveAttr;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.renderer.Html;
import org.skatiger.jrove.renderer.HtmlRendererBase;
import org.skatiger.jrove.renderer.RendererUtils;
import org.skatiger.jrove.util.StringUtils;

public class HtmlLabelRenderer extends HtmlRendererBase {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
            .getLogger(HtmlLabelRenderer.class);

    @Override
    public void encodeBegin(ViewContext context, UIComponent component)
            throws IOException {
        super.encodeBegin(context, component);
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(Html.LABEL_ATTR, component);
        String _for = (String) component.getAttributes()
                .get(JroveAttr.FOR_ATTR);
        renderId(context, component);
        if (StringUtils.isNotEmpty(_for)) {
            UIComponent forcomponent = context.getViewRoot().getComponentMap()
                    .get(_for);
            if (forcomponent != null) {
                String clientId = forcomponent.getClientId(context);
                RendererUtils.renderHtmlAttributeValue(writer, Html.FOR_ATTR,
                        JroveAttr.FOR_ATTR, clientId);
            } else {
                logger.warn("component with name " + _for
                        + " not found in component tree");
            }
        }
        RendererUtils.renderHtmlStandardAttributes(writer, component);
    }

    @Override
    public void encodeEnd(ViewContext context, UIComponent component)
            throws IOException {
        super.encodeEnd(context, component);
        ResponseWriter writer = context.getResponseWriter();
        writer.endElement(Html.LABEL_ATTR);
    }
}
